<script lang="ts" setup>
import { ref, watchEffect } from "vue";
import { cloneDeep } from "lodash";
import { useRouter } from "vue-router";
import { showToast } from "vant";

const items = [
  {
    text: "浙江",
    children: [
      { text: "杭州", id: "杭州" },
      { text: "温州", id: "温州" },
      { text: "宁波", id: "宁波", disabled: false },
    ],
  },
  {
    text: "江苏",
    children: [
      { text: "南京", id: "南京" },
      { text: "无锡", id: "无锡" },
      { text: "徐州", id: "徐州" },
    ],
  },
  { text: "福建", disabled: true },
];

const router = useRouter();
const value = ref("");
const tagList = ref(cloneDeep(items));
const activeIds = ref<string[]>([]);
const activeIndex = ref(0);
let searchTimer: ReturnType<typeof setTimeout>;

watchEffect(() => {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(() => handleSearch(value.value), 300);
});

const handleSearch = (val: string) => {
  if (!val) {
    tagList.value = cloneDeep(items);
    return;
  }

  tagList.value = cloneDeep(items)
    .map(parentTag => ({
      ...parentTag,
      children: parentTag.children?.filter(item =>
        item.text.includes(val)
      )
    }))
    .filter(parentTag =>
      parentTag.children?.length || parentTag.text.includes(val)
    );
};

const onCancel = () => {
  value.value = "";
  tagList.value = cloneDeep(items);
};

const doClose = (tag: string) => {
  activeIds.value = activeIds.value.filter(item => item !== tag);
};

const doSearchResult = () => {
  if (!activeIds.value.length) {
    showToast("请先选择至少一个标签");
    return;
  }
  router.push({
    path: "/user/list",
    query: { tags: activeIds.value }
  });
};
</script>

<template>
  <div class="container">
    <!-- 搜索框 -->
    <van-search
      v-model="value"
      shape="round"
      placeholder="请输入标签名称"
      background="#f8f8f8"
      @cancel="onCancel"
    />

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <!-- 已选标签 -->
      <div class="selected-section">
        <van-divider
          :style="{ color: '#666', borderColor: '#eee', margin: '12px 0' }"
          content-position="left"
        >
          已选标签（{{ activeIds.length }}）
        </van-divider>
        <div v-if="!activeIds.length" class="empty-tips">
          <van-icon name="info" color="#999" />
          <span>暂未选择任何标签</span>
        </div>
        <div v-else class="tags-container">
          <van-tag
            v-for="tag in activeIds"
            :key="tag"
            round
            closeable
            size="medium"
            color="#409eff"
            text-color="#fff"
            @close="doClose(tag)"
          >
            {{ tag }}
          </van-tag>
        </div>
      </div>

      <!-- 可选标签 -->
      <van-divider
        :style="{ color: '#666', borderColor: '#eee', margin: '12px 0' }"
        content-position="left"
      >
        可选标签
      </van-divider>

      <van-tree-select
        v-model:active-id="activeIds"
        v-model:main-active-index="activeIndex"
        :items="tagList"
        class="tree-select"
        :main-active-color="'#409eff'"
        :content-active-color="'#409eff'"
      />
    </div>

    <!-- 吸底按钮 -->
    <div class="fixed-footer">
      <van-button
        round
        type="primary"
        block
        @click="doSearchResult"
        :disabled="!activeIds.length"
      >
        立即搜索（{{ activeIds.length }}）
      </van-button>
    </div>
  </div>
</template>

<style scoped lang="less">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f8f8f8;

  .van-search {
    padding: 8px 12px;
    background: #fff;
  }

  .content-wrapper {
    flex: 1;
    overflow-y: auto;
    padding: 0 12px;
  }

  .selected-section {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-top: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.03);

    .empty-tips {
      display: flex;
      align-items: center;
      padding: 8px;
      color: #999;
      font-size: 14px;

      .van-icon {
        margin-right: 6px;
      }
    }
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .van-tag {
      transition: transform 0.2s;

      &:active {
        transform: scale(0.95);
      }
    }
  }

  .tree-select {
    margin-top: 12px;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0,0,0,0.03);

    :deep(.van-tree-select__item) {
      font-size: 14px;
      padding: 12px;
    }

    :deep(.van-tree-select__content) {
      background: #fafafa;
    }
  }

  .fixed-footer {
    flex-shrink: 0;
    padding: 12px;
    background: #fff;
    box-shadow: 0 -2px 12px rgba(0,0,0,0.05);

    .van-button {
      height: 44px;
      font-size: 16px;
      font-weight: 500;

      &--disabled {
        opacity: 0.6;
      }
    }
  }
}
</style>
